<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');


/**
 * This class is for online shop order process - payment.
 * params order step
 * This is the children of controller.
 * PHP5 CMS Typolight
 * Copyright is 34n.sam@gmail.com
 */
 
 /**
 * Start page
 */
session_start();

require_once('system/libraries/currency.php');

$backpocket = new GetBackPocket();
$backpocket->run();

class GetBackPocket extends Controller
{	
	/**
	 * This is class construct function.
	 * @params null
	 * @Return null
	 */
	public function __construct()
	{
		parent::__construct();
		$this->obj_currency = new Currency();
	}
	
	/** 
	 * Start page function
	 * @params null
	 * @Return null
	 */
	public function run()
	{
		if (FE_USER_LOGGED_IN)
		{
			$this->import('Database');
			$this->import("FrontendUser", "User");
			$this->loadDataContainer("tl_member");
		
			$mainPath = "<div class=\"path\">
							<a title=\"HOME\" href=\"profile.html\">
								HOME&nbsp;" . htmlentities('>') . "&nbsp;" . (($this->User->firstname) ? $this->User->firstname : $this->User->email) . "'s account
							</a>
						</div>
						<div class=\"quick_tool\">
							<a title=\"ORDER STATUS\" href=\"order-status.html\">ORDER STATUS</a> 
							<a href=\"profile_detail.html\" title=\"PROFILE\">PROFILE</a> 
							<a title=\"WISHLIST\" href=\"backpocket.html\" class=\"active\">WISHLIST</a> 
							<a title=\"ADDRESS BOOK\" href=\"shipping_payment.html\">ADDRESS BOOK</a>
						</div>";

			if (isset($_GET['registration']) && $_GET['registration'] && $_GET['registration'] == 'success')
			{
				$mainHead = "<div class=\"result_info\">
			<p>Your account has been created!</p>
			<p>A confirmation has been sent to the provided email address. If you have any question about the operation of this online shop, please email us.</p>
			<p>Happy shopping. Start here.</p>
		</div> <!-- result_info end -->";
			}
			
			echo $mainPath . $mainHead . $this->displayBackpocket();
		}
		else
		{
			$this->redirect("sign-in.html");
		}
	}
	
	/**
	 * Generate and display Backpocket
	 * @params null
	 * @Return string
	 */
	private function displayBackpocket()
	{
		$strIds = "";
		$totalPrice = 0;
		$arrBackProducts = array();
		
		// Import frontend user.
		$this->import('FrontendUser', 'User');
		$this->loadDataContainer('tl_member');
		
		if (isset($_SESSION['FE_DATA']['referer']) && $_SESSION['FE_DATA']['referer'])
		{
			if (isset($_SESSION['FE_DATA']['referer']['current']) && $_SESSION['FE_DATA']['referer']['current'] && strpos($_SESSION['FE_DATA']['referer']['current'], 'referer') !== false)
			{
				if (isset($_SESSION['BACKPOCKET']) && $_SESSION['BACKPOCKET'])
				{				
					$objInsertId = $this->Database->prepare("INSERT INTO `tl_backpocket` (`id_member`, `id_catalog`, `tstamp`, `size`, `color`, `quantity`) VALUES (?, ?, ?, ?, ?, ?)")
									->execute($this->User->id, $_SESSION['BACKPOCKET'][0]['id'], time(), $_SESSION['BACKPOCKET'][0]['size'], $_SESSION['BACKPOCKET'][0]['color'], $_SESSION['BACKPOCKET'][0]['quantity']);
				}
			}
		}
		
		// Get the backpocket from database.
		$objBackPocket = $this->Database->prepare("SELECT bp.*, cata.*, tmy.`name` as categoryName, cat_color.`id` AS id_color, bp.size AS bpSize, ca.`id_size` AS pro_size, ca.`id_color` AS pro_color, ca.`catalog_stock` AS stock 
													FROM `tl_backpocket` AS bp
													INNER JOIN `product_catalog` AS cata ON cata.`id`=bp.`id_catalog`
													INNER JOIN `tl_taxonomy` AS tmy ON tmy.`id`=cata.`category`
													LEFT JOIN `catalog_colour` AS cat_color ON cat_color.`title`=bp.`color`
													LEFT JOIN `tl_catalog_attribute` AS ca ON ca.`id_catalog`=bp.`id_catalog`
													WHERE bp.`id_member`=?
													ORDER BY bp.`tstamp` DESC")
										->execute($this->User->id);
		
		if ($objBackPocket->numRows < 1)
		{
			return "<div class=\"none_backpocket\">There is no item in your wishlist.</div>";
		}		
		
		$strHtml = '<script type="text/javascript">
						function fn_add_to_cart(node)
						{
							jQuery("div#head_add_to_cart").hide();
							jQuery(".update_success_msg").hide();
							jQuery("div#cart_out_of_stock").hide();
							jQuery("div#car_overed_stock").hide();
							jQuery("div#item_added").hide();
							
							var product_id = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id\']").val();
							var product_skuid = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'skuid\']").val();
							var prodcut_name = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'prodcut_name\']").val();
							var product_price = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'price\']").val();
							var product_colour = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val();
							var product_size = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val();
							var product_colour_ids = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val();
							var product_size_ids = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val();
							var product_quantity = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val();
							var product_is_wrapping = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'is_wrapping\']").val();
							var product_wrapping_price = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'wrapping_price\']").val();
							jQuery.ajax({
								 type: "POST",
								 url: "addToCart.php",
								 data: "FORM_SUBMIT=addtocart&id=" + product_id + "&skuid=" + product_skuid + "&prodcut_name=" + prodcut_name + "&price=" + product_price + "&colour=" + product_colour + "&size=" + product_size + "&colour_ids=" + product_colour_ids + "&size_ids=" + product_size_ids + "&quantity=" + product_quantity + "&is_wrapping=" + product_is_wrapping + "&wrapping_price=" + product_wrapping_price,
								 success: function(msg){ 
									//alert( "Data Saved: " +   msg );
									var arrValues = eval(msg);
									if (arrValues[0].status == \'1\')
									{
										jQuery("#item_added").show();
									}
									else
									{
										jQuery("#item_added").hide();
										jQuery("a.cart").html(\'Shopping Cart(\' + arrValues[0].quantity + \')\');
										jQuery("div#head_add_to_cart").show();
									}
								} 
							});
							
							return false;
						}
						
						function fn_update_backpocket(node)
						{
							jQuery("div#head_add_to_cart").hide();
							jQuery(".update_success_msg").hide();
							jQuery("div#cart_out_of_stock").hide();
							jQuery("div#car_overed_stock").hide();
							jQuery("div#item_added").hide();
							
							var product_id = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id\']").val();
							var product_skuid = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'skuid\']").val();
							var prodcut_name = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'prodcut_name\']").val();
							var product_price = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'price\']").val();
							var product_colour = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val();
							var product_size = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val();
							var product_colour_ids = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val();
							var product_size_ids = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val();
							var product_quantity = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val();
							var product_is_wrapping = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'is_wrapping\']").val();
							var product_sessionID = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'sessionID\']").val();
							var product_id_backpocket = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id_backpocket\']").val();
							var bp_id_member = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id_member\']").val();
							
							jQuery.ajax({
								 type: "POST",
								 url: "addToCart.php",
								 data: "FORM_SUBMIT=updatebackpocket&id=" + product_id + "&skuid=" + product_skuid + "&prodcut_name=" + prodcut_name + "&price=" + product_price + "&colour=" + product_colour + "&size=" + product_size + "&colour_ids=" + product_colour_ids + "&size_ids=" + product_size_ids + "&quantity=" + product_quantity + "&is_wrapping=" + product_is_wrapping + "&sessionID=" + product_sessionID + "&id_backpocket=" + product_id_backpocket + "&id_member=" + bp_id_member,
								 success: function(msg){ 
									/*alert( "Data Saved: " +   msg );*/
									if (msg != \'false\')
									{
										//jQuery(".update_success_msg").show();
										var arrMsg = msg.split(\'::\');
										if (arrMsg[1] == undefined) {
											jQuery("div#cart_out_of_stock").show();
											jQuery(".update_success_msg").hide();
											return false;
										}
										var arrSession_id = arrMsg[1].split(\'=\');
										var strUrl = window.location.href;
										if (strUrl.indexOf("?") > -1)
											strUrl = strUrl.substring(0, strUrl.indexOf("?"));
										strUrl = strUrl + "?updatesuccess=1&session_id=" + arrSession_id[1];
										window.location = strUrl;
									}
									else
									{
										jQuery("div#cart_out_of_stock").show();
										jQuery(".update_success_msg").hide();
									}
								} 
							});
								
							return false;
						}
						
						function fn_remove_backpocket(node)
						{			
							jQuery("div#head_add_to_cart").hide();
							jQuery(".update_success_msg").hide();
							jQuery("div#cart_out_of_stock").hide();
							jQuery("div#car_overed_stock").hide();
							jQuery("div#item_added").hide();
							
							var product_id_backpocket = jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id_backpocket\']").val();

							jQuery.ajax({
								 type: "POST",
								 url: "addToCart.php",
								 data: "FORM_SUBMIT=removefrombackpocket&id_backpocket=" + product_id_backpocket,
								 success: function(msg){ 
									/*alert( "Data Saved: " +   msg );*/											
									if (msg == \'success\')
									{
										//alert(\'Delete successfully!\');
										var strUrl = window.location.toString();
										if (strUrl.indexOf("?updatesuccess") > -1)
											window.location.href = strUrl.substring(0, strUrl.indexOf("?updatesuccess"));
										else
											window.location.href = strUrl;
									}
								} 
							});
							
							return false;
						}
						
						jQuery(function(){
							jQuery("a[@name=\'add_to_cart\']").click(function(){
								jQuery("div#head_add_to_cart").hide();
								jQuery(".update_success_msg").hide();
								jQuery("div#cart_out_of_stock").hide();
								jQuery("div#car_overed_stock").hide();
								jQuery("div#item_added").hide();
								
								var product_id = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id\']").val();
								var product_skuid = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'skuid\']").val();
								var prodcut_name = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'prodcut_name\']").val();
								var product_price = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'price\']").val();
								var product_colour = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val();
								var product_size = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val();
								var product_colour_ids = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val();
								var product_size_ids = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val();
								var product_quantity = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val();
								var product_is_wrapping = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'is_wrapping\']").val();
								var product_wrapping_price = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'wrapping_price\']").val();
								
								jQuery.ajax({
									 type: "POST",
									 url: "addToCart.php",
									 data: "FORM_SUBMIT=addtocart&id=" + product_id + "&skuid=" + product_skuid + "&prodcut_name=" + prodcut_name + "&price=" + product_price + "&colour=" + product_colour + "&size=" + product_size + "&colour_ids=" + product_colour_ids + "&size_ids=" + product_size_ids + "&quantity=" + product_quantity + "&is_wrapping=" + product_is_wrapping + "&wrapping_price=" + product_wrapping_price,
									 success: function(msg){ 
										//alert( "Data Saved: " +   msg );
										var arrValues = eval(msg);
										if (arrValues[0].status == \'1\')
										{
											jQuery("#item_added").show();
										}
										else
										{
											jQuery("#item_added").hide();
											jQuery("a.cart").html(\'Shopping Cart(\' + arrValues[0].quantity + \')\');
											jQuery("div#head_add_to_cart").show();
										}											
									} 
								});
								
								return false;
							});
							
							jQuery("a[@name=\'Update_backpocket\']").click(function(){
								jQuery("div#head_add_to_cart").hide();
								jQuery(".update_success_msg").hide();
								jQuery("div#cart_out_of_stock").hide();
								jQuery("div#car_overed_stock").hide();
								jQuery("div#item_added").hide();
								
								var product_id = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id\']").val();
								var product_skuid = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'skuid\']").val();
								var prodcut_name = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'prodcut_name\']").val();
								var product_price = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'price\']").val();
								var product_colour = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val();
								var product_size = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val();
								var product_colour_ids = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val();
								var product_size_ids = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val();
								var product_quantity = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val();
								var product_is_wrapping = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'is_wrapping\']").val();
								var product_sessionID = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'sessionID\']").val();
								var product_id_backpocket = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id_backpocket\']").val();
								var bp_id_member = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id_member\']").val();
								
								jQuery.ajax({
									 type: "POST",
									 url: "addToCart.php",
									 data: "FORM_SUBMIT=updatebackpocket&id=" + product_id + "&skuid=" + product_skuid + "&prodcut_name=" + prodcut_name + "&price=" + product_price + "&colour=" + product_colour + "&size=" + product_size + "&colour_ids=" + product_colour_ids + "&size_ids=" + product_size_ids + "&quantity=" + product_quantity + "&is_wrapping=" + product_is_wrapping + "&sessionID=" + product_sessionID + "&id_backpocket=" + product_id_backpocket + "&id_member=" + bp_id_member,
									 success: function(msg){ 
										//alert( "Data Saved: " +   msg );
										if (msg != \'false\')
										{
											//jQuery(".update_success_msg").show();
											var arrMsg = msg.split(\'::\');
											var arrSession_id = arrMsg[1].split(\'=\');
											var strUrl = window.location.href;
											if (strUrl.indexOf("?") > -1)
												strUrl = strUrl.substring(0, strUrl.indexOf("?"));
											strUrl = strUrl + "?updatesuccess=1&session_id=" + arrSession_id[1];
											window.location = strUrl;

										}
										else
										{
											jQuery("div#cart_out_of_stock").show();
											jQuery(".update_success_msg").hide();
										}
									} 
								});
								
								return false;
							});
							
							jQuery("a[@name=\'remove_backpocket\']").click(function(){
								jQuery("div#head_add_to_cart").hide();
								jQuery(".update_success_msg").hide();
								jQuery("div#cart_out_of_stock").hide();
								jQuery("div#car_overed_stock").hide();
								jQuery("div#item_added").hide();
							
								var product_id_backpocket = jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id_backpocket\']").val();

								jQuery.ajax({
									 type: "POST",
									 url: "addToCart.php",
									 data: "FORM_SUBMIT=removefrombackpocket&id_backpocket=" + product_id_backpocket,
									 success: function(msg){ 
										//alert( "Data Saved: " +   msg );											
										if (msg == \'success\')
										{
											//alert(\'Delete successfully!\');
											var strUrl = window.location.toString();
											if (strUrl.indexOf("?updatesuccess") > -1)
												window.location.href = strUrl.substring(0, strUrl.indexOf("?updatesuccess"));
											else
												window.location.href = strUrl;
										}

									} 
								});
								
								return false;
							});
							
						});
						
						// function for onchange.
						function changeColor(node)
						{
							jQuery("div#head_add_to_cart").hide();
							jQuery(".update_success_msg").hide();
							jQuery("div#cart_out_of_stock").hide();
							jQuery("div#car_overed_stock").hide();
							jQuery("div#item_added").hide();
							
							jQuery.ajax({
								 type: "POST",
								 url: "changeBackpocket.php",
								 data: "FORM_SUBMIT=changeCart&color=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'sessionID\']").val(),
								 success: function(msg){ 
									//alert( "Data Saved: " +   msg );
									if (msg != \'false\')
									{
										//var objHtml = {"method": "newURI"};
										var objHtml = eval(msg);
										//alert(jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html());
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_info").html(objHtml[0].td_info);
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("div.skin").html(objHtml[0].td_skin);
						
										//jQuery("#cart_out_of_stock").hide();
									}
									else
									{
										//jQuery("#cart_out_of_stock").show();
									}
								} 
							});
						}
						
						// function for onchange.
						function changeSize(node)
						{
							jQuery("div#head_add_to_cart").hide();
							jQuery(".update_success_msg").hide();
							jQuery("div#cart_out_of_stock").hide();
							jQuery("div#car_overed_stock").hide();
							jQuery("div#item_added").hide();
							
							jQuery.ajax({
								 type: "POST",
								 url: "changeBackpocket.php",
								 data: "FORM_SUBMIT=changeCart&color=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val() + "&size=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'sessionID\']").val(),
								 success: function(msg){ 
									//alert( "Data Saved: " +   msg );
									if (msg != \'false\')
									{
										//var objHtml = {"method": "newURI"};
										var objHtml = eval(msg);
										//alert(jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html());
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_info").html(objHtml[0].td_info);
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("div.skin").html(objHtml[0].td_skin);
						
										//jQuery("#cart_out_of_stock").hide();
									}
									else
									{
										//jQuery("#cart_out_of_stock").show();
									}
								} 
							});
						}
						
						// function for onchange.
						function changeQuantity(node)
						{
							jQuery("div#head_add_to_cart").hide();
							jQuery(".update_success_msg").hide();
							jQuery("div#cart_out_of_stock").hide();
							jQuery("div#car_overed_stock").hide();
							jQuery("div#item_added").hide();
							
							jQuery.ajax({
								 type: "POST",
								 url: "changeBackpocket.php",
								 data: "FORM_SUBMIT=changeCart&color=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'color\']").val() + "&size=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val()  + "&quantity=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'sessionID\']").val(),
								 success: function(msg){ 
									//alert( "Data Saved: " +   msg );
									if (msg != \'false\')
									{
										//var objHtml = {"method": "newURI"};
										var objHtml = eval(msg);
										//alert(jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html());
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_info").html(objHtml[0].td_info);
										jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("div.skin").html(objHtml[0].td_skin);
						
										//jQuery("#cart_out_of_stock").hide();
									}
									else
									{
										//jQuery("#cart_out_of_stock").show();
									}
								} 
							});
						}
					</script>		
		<h3>WISHLIST</h3>';
		
		$arrBackPockets = array();
		$id_bp = 0;
		while ($objBackPocket->next())
		{
			if ($id_bp != $objBackPocket->id_backpocket)
			{
				$strSizeids = "";
				$objCataAttributes = $this->Database->prepare("SELECT * FROM `tl_catalog_attribute` WHERE `id_catalog`=? AND `id_color`=?")
													->execute($objBackPocket->id, $objBackPocket->id_color);			
				if ($objCataAttributes->numRows > 0)
				{
					while ($objCataAttributes->next())
					{
						$strSizeids .= $objCataAttributes->id_size . ",";
					}
				}
				
				if (strpos($strSizeids, ',') !== false)
				{
					$strSizeids = substr($strSizeids, 0, strlen($strSizeids) - 1);
				}
				
				$sessionID	= $objBackPocket->id."_".$objBackPocket->color."_".trim(strtolower($objBackPocket->bpSize));
				$objBackPocket->size = $strSizeids;					
			
				$arrBackPockets[$objBackPocket->id_backpocket] = array(
					'id' => $objBackPocket->id,
					'color' => $objBackPocket->color,					
					'bpSize' => $objBackPocket->bpSize,
					'skuid' => $objBackPocket->skuid,
					'category' => $objBackPocket->category,
					'id_color' => $objBackPocket->id_color,
					'name' => $objBackPocket->name,
					'price' => $objBackPocket->price,
					'is_wrapping' => $objBackPocket->is_wrapping,
					'wrapping_price' => $objBackPocket->wrapping_price,					
					'id_backpocket' => $objBackPocket->id_backpocket,
					'id_member' => $objBackPocket->id_member, 	
					'quantity' => intval($objBackPocket->quantity)
				);
			}
			
			//if (($objBackPocket->stock > 0 && intval($objBackPocket->quantity) > 0) || ($objBackPocket->pro_color == $objBackPocket->id_color && $objBackPocket->bpSize == $objBackPocket->pro_size))
			//{
				if (!isset($arrBackPockets[$objBackPocket->id_backpocket]['colour'][$objBackPocket->pro_color][$objBackPocket->pro_size]))
				{
					$arrBackPockets[$objBackPocket->id_backpocket]['colour'][$objBackPocket->pro_color][$objBackPocket->pro_size] = array();
				}
					
				$arrBackPockets[$objBackPocket->id_backpocket]['colour'][$objBackPocket->pro_color][$objBackPocket->pro_size][] = $objBackPocket->stock;
				//'size' => $objBackPocket->size,
				//'colour' => $objBackPocket->colour,	
			//}
			//else
			//{
				//$arrBackPockets[$objBackPocket->id_backpocket]['colour'] = array();
			//}
			$id_bp = $objBackPocket->id_backpocket;
		}
		//print_r($arrBackPockets);exit;
		foreach ($arrBackPockets as $key=>$arraBPInfo)
		{
			if (isset($arraBPInfo['colour'][$arraBPInfo['id_color']]) && $arraBPInfo['colour'][$arraBPInfo['id_color']])
				$arraBPInfo['size_ids'] = implode(',', array_keys($arraBPInfo['colour'][$arraBPInfo['id_color']]));
			if (isset($arraBPInfo['colour']) && $arraBPInfo['colour'])
				$arraBPInfo['color_ids'] = implode(',', array_keys($arraBPInfo['colour']));
			
			$sessionID	= $arraBPInfo['id']."_".$arraBPInfo['color']."_".trim(strtolower($arraBPInfo['bpSize']));
			
			$is_noneStock = false;
			$is_overStock = false;
			$quantity = intval($arraBPInfo['quantity']);
			
			// Get product attribute.
			$strStock = $this->getCurrentStockInfo($arraBPInfo['id'], trim($arraBPInfo['color']), $arraBPInfo['bpSize']);
			 
			// Stock information deal with.
			if (is_null($strStock))
			{
				$is_noneStock = true;
			}
			elseif (!$strStock)
			{
				$is_noneStock = true;
			}
			else 
			{
				$is_noneStock = false;
				if ($quantity > $strStock)
				{
					$quantity = $strStock;
					$is_overStock = true;
				}
				else 
					$is_overStock = false;
			}
			
			//$strHtml .= '<div class="error" '. ((!$is_noneStock) ? ' style="display:none"' : '' ) . ' id="cart_out_of_stock">The quantity of this product is out of stock. Please select again.</div>';
			$sessionID	= $arraBPInfo['id']."_".$arraBPInfo['bpSize']."_".trim(strtolower($arraBPInfo['color']));
			
			$strHtml .= '<div id="head_add_to_cart" class="error" style="display:none;">Item(s) added to your cart</div><div class="update_success_msg"' . ((!$this->Input->get('updatesuccess') || $sessionID != $this->Input->get('session_id')) ? ' style="display:none;"' : '') .' class="error">Your wishlist is updated.</div>';
			$strHtml .= '<div class="error" style="display:none" id="cart_out_of_stock">The quantity of this product is out of stock. Please select again.</div>';
			$strHtml .= '<div class="error" '. ((!$is_overStock) ? ' style="display:none"' : '' ) . ' id="car_overed_stock">This item is currently out of stock.</div>';
			$strHtml .= '<div class="error" style="display:none" id="item_added">The item(s) is already in your cart. If you\'d like to add more, please go to shopping cart and update the quantity.</div>';
			
			$imgPath = "daft_files/catalog/products/" . $arraBPInfo['skuid'] . "/" . $arraBPInfo['color'] . "/1.jpg";
			$strHtml .= '<script type="text/javascript">
							jQuery(function(){
								jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'color\']").change(function(){
									jQuery("div#head_add_to_cart").hide();
									jQuery("#bk_pocket_' . $sessionID . '").find(".update_success_msg").hide();
									jQuery("div#cart_out_of_stock").hide();
									jQuery("div#car_overed_stock").hide();
									jQuery("div#item_added").hide();
							
									jQuery.ajax({
										 type: "POST",
										 url: "changeBackpocket.php",
										 data: "FORM_SUBMIT=changeCart&color=" + jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'color\']").val() + "&session_id=" + jQuery("#bk_pocket_' . $sessionID . '").find("input[@name=\'sessionID\']").val(),
										 success: function(msg){ 
											//alert( "Data Saved: " +   msg );
											if (msg != \'false\')
											{
												//var objHtml = {"method": "newURI"};
												var objHtml = eval(msg);
												//alert(objHtml[0].td_skin);
												jQuery("#bk_pocket_' . $sessionID . '").find("div.skin").html(objHtml[0].td_skin);
												jQuery("#bk_pocket_' . $sessionID . '").find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
												jQuery("#bk_pocket_' . $sessionID . '").find("table.cart_item td.td_info").html(objHtml[0].td_info);
								
												//jQuery("#cart_out_of_stock").hide();
											}
											else
											{
												//jQuery("#cart_out_of_stock").show();
											}
										} 
									});
								});
								jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'size\']").change(function(){
									
									jQuery("div#head_add_to_cart").hide();
									jQuery("#bk_pocket_' . $sessionID . '").find(".update_success_msg").hide();
									jQuery("div#cart_out_of_stock").hide();
									jQuery("div#car_overed_stock").hide();
									jQuery("div#item_added").hide();
							
									jQuery.ajax({
										 type: "POST",
										 url: "changeBackpocket.php",
										 data: "FORM_SUBMIT=changeCart&size=" + jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'size\']").val() + "&color=" + jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'color\']").val() + "&session_id=" + jQuery("#bk_pocket_' . $sessionID . '").find("input[@name=\'sessionID\']").val(),
										 success: function(msg){ 
											//alert( "Data Saved: " +   msg );
											if (msg != \'false\')
											{
												//var objHtml = {"method": "newURI"};
												var objHtml = eval(msg);
												//alert(objHtml[0].td_skin);
												jQuery("#bk_pocket_' . $sessionID . '").find("div.skin").html(objHtml[0].td_skin);
												jQuery("#bk_pocket_' . $sessionID . '").find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
												jQuery("#bk_pocket_' . $sessionID . '").find("table.cart_item td.td_info").html(objHtml[0].td_info);
								
												//jQuery("#cart_out_of_stock").hide();
											}
											else
											{
												//jQuery("#cart_out_of_stock").show();
											}
										} 
									});
								});
								
								jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'quantity\']").change(function(){
									jQuery("div#head_add_to_cart").hide();
									jQuery("#bk_pocket_' . $sessionID . '").find(".update_success_msg").hide();
									jQuery("div#cart_out_of_stock").hide();
									jQuery("div#car_overed_stock").hide();
									jQuery("div.update_success_msg").hide();
									jQuery("div#item_added").hide();
							
									jQuery.ajax({
										 type: "POST",
										 url: "changeBackpocket.php",
										 data: "FORM_SUBMIT=changeCart&size=" + jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'size\']").val() + "&color=" + jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'color\']").val() + "&quantity=" + jQuery("#bk_pocket_' . $sessionID . '").find("select[@name=\'quantity\']").val() + "&session_id=" + jQuery("#bk_pocket_' . $sessionID . '").find("input[@name=\'sessionID\']").val(),
										 success: function(msg){ 
											//alert( "Data Saved: " +   msg );
											if (msg != \'false\')
											{
												//var objHtml = {"method": "newURI"};
												var objHtml = eval(msg);
												//alert(objHtml[0].td_skin);
												jQuery("#bk_pocket_' . $sessionID . '").find("div.skin").html(objHtml[0].td_skin);
												jQuery("#bk_pocket_' . $sessionID . '").find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
												jQuery("#bk_pocket_' . $sessionID . '").find("table.cart_item td.td_info").html(objHtml[0].td_info);
								
												//jQuery("#cart_out_of_stock").hide();
											}
											else
											{
												//jQuery("#cart_out_of_stock").show();
											}
										} 
									});
								});
							});							
						</script>
					<div id="bk_pocket_' . $sessionID . '">
					<table class="cart_item">
					<tr>
					<td rowspan="2" class="td_pic">'
						 . (($arraBPInfo['id_color'] && $arraBPInfo['id_color']!= 'undefined' && $arraBPInfo['bpSize'] && $arraBPInfo['bpSize'] != 'undefined') ? '<a href="./product.html?category='.$arraBPInfo['category'].'&id='.$arraBPInfo['id'].'&id_colour=' . $arraBPInfo['id_color'] . '&id_size=' . $arraBPInfo['bpSize'] . '">
							<img src="image.php?src=' . $imgPath . '&height=79&width=79" alt="" /></a>' : '') . '
					</td>
					<td class="td_info">
						<h4>' . (($arraBPInfo['id_color'] && $arraBPInfo['id_color']!= 'undefined' && $arraBPInfo['bpSize'] && $arraBPInfo['bpSize'] != 'undefined') ? '<a href="./product.html?category='.$arraBPInfo['category'].'&id='.$arraBPInfo['id'].'&id_colour=' . $arraBPInfo['id_color']  . '&id_size=' . $arraBPInfo['bpSize'] . '">' : '') . $arraBPInfo['name'] . (($arraBPInfo['id_color'] && $arraBPInfo['id_color']!= 'undefined' && $arraBPInfo['bpSize'] && $arraBPInfo['bpSize'] != 'undefined') ? '</a>' : '') . '</h4>
						<small>SKU #' . $arraBPInfo['skuid'] . '</small><br />
						<small> ' . $this->obj_currency->change_order(number_format($arraBPInfo['price'], 2, '.', '')) . (($arraBPInfo['is_wrapping'] && $arraBPInfo['wrapping_price'] > 0) ? '<br /><small>GIFT WRAPPING ' . $this->obj_currency->change_order(number_format($arraBPInfo['wrapping_price'], 2, '.', '')) . '</small>' : '') . (($is_noneStock) ? '<br /><span class="error">Out of stock - Please remove from your wishlist.</span>' : '') . '
					</td>
					<td rowspan="2" class="td_skin">
						<div class="skin">
							<p>
								<label>COLOR</label>'
								. (($arraBPInfo['colour']) ? 
								('<select name="color" class="color">
									'.$this->setColour($arraBPInfo['color'], implode(',', array_keys($arraBPInfo['colour']))).'
								</select>
								<a href="#" title="ADD TO CART" name="add_to_cart" class="update">ADD TO CART</a>') : '<a href="#" title="" class="update" name="remove_backpocket">REMOVE FROM WISHLIST</a>') . '
							</p>
							<p>
								<label>SIZE</label>'
								. (($arraBPInfo['colour'][$arraBPInfo['id_color']]) ? ('
								<select name="size" class="size">
									'.$this->setSize($arraBPInfo['bpSize'], implode(',', array_keys($arraBPInfo['colour'][$arraBPInfo['id_color']]))).'
								</select>
								<a href="#" title="UPDATE WISHLIST" class="update" name="Update_backpocket">UPDATE WISHLIST</a>') : '') . '
							</p>
							<p>
								<label>QUANTITY</label>
								' . ((!$is_noneStock) ? '
								<select name="quantity" class="color">
								'.$this->setQuantity($quantity, $strStock).'
								</select>' : '') . (($arraBPInfo['colour']) ? '
								<a href="#" title="" class="update" name="remove_backpocket">REMOVE FROM WISHLIST</a>' : '') . '
							</p>
						</div>
					</td>
					<td rowspan="2" class="unit_price"><strong>' . (($arraBPInfo['is_wrapping']) ? $this->obj_currency->change_order(number_format(($arraBPInfo['price']) * $quantity + $arraBPInfo['wrapping_price'], 2, '.', '')) : $this->obj_currency->change_order(number_format($arraBPInfo['price'] * $quantity, 2, '.', ''))) . '</strong></td>
				</tr>
			</table>
			<input type="hidden" value="addtocart" name="FORM_SUBMIT"/>
			<input type="hidden" value="'.$arraBPInfo['id'].'" name="id"/>
			<input type="hidden" value="'.$arraBPInfo['skuid'].'" name="skuid"/>
			<input type="hidden" value="'.$arraBPInfo['name'].'" name="prodcut_name"/>
			<input type="hidden" value="'. (intval($arraBPInfo['is_wrapping']) ? ($arraBPInfo['price'] + $arraBPInfo['wrapping_price']) : $arraBPInfo['price']) .'" name="price"/>
		<input type="hidden" value="'.$arraBPInfo['color_ids'].'" name="colour_ids"/>
			<input type="hidden" value="'.$arraBPInfo['size_ids'].'" name="size_ids"/>
			<input type="hidden" value="'.$arraBPInfo['is_wrapping'].'" name="is_wrapping"/>
			<input type="hidden" value="'.$arraBPInfo['wrapping_price'].'" name="wrapping_price"/>
			<input type="hidden" value="'.$sessionID.'" name="sessionID"/>
			<input type="hidden" value="'.$arraBPInfo['id_backpocket'].'" name="id_backpocket"/>
			<input type="hidden" value="' . $arraBPInfo['id_member'] . '" name="id_member"/>
			</div>';
			
			$totalPrice += ($arraBPInfo['is_wrapping']) ? number_format(($arraBPInfo['price'] + $arraBPInfo['wrapping_price']), 2, '.', '') : number_format($arraBPInfo['price'], 2, '.', '');
		}
		
		return $strHtml;
	}
	
/**
	 * This function get the stock of this special product and current quantity.
	 * @param int $id_catalog
	 * @param string $colour
	 * @param int $size
	 * @return int currentStock
	 */
	public function getCurrentStockInfo($id_catalog=0, $colour=0, $size=0)
	{
		if (!$id_catalog || !$colour || !$size)
			return null;
		// Get the colour id.
		$this->import("Database");
		$strSQL = "SELECT `id` FROM `catalog_colour` WHERE `title`=?";
		$objId_colour = $this->Database->prepare($strSQL)
							->execute($colour, time(), time());
		
		if ($objId_colour->numRows < 1)
			return null;
		
		$id_colour = $objId_colour->id;
		
		// Get the stock of this special product.
		$strSQL = "SELECT * FROM `tl_catalog_attribute` WHERE `id_catalog`=? AND `id_color`=? AND `id_size`=?";
		$objSock = $this->Database->prepare($strSQL)
								->execute($id_catalog, $id_colour, $size);
		if ($objSock->numRows < 1)
			return null;
		
		$cnt_stock = intval($objSock->catalog_stock);
		
		return $cnt_stock;
	}
	
	private function setColour($colour,$colour_ids)
	{
		$colourList = $this->getColour();
		$colours = explode(",", $colour_ids);
		
		$strHTML = "";
		for($i=0;$i<count($colours);$i++){
			$key  	  = $colours[$i];
			$selected = ($colour == $colourList[$key]['title']) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$colourList[$key]['title'].'" '.$selected.'>'.$colourList[$key]['title'].'</option>\n';
		}
		
		return $strHTML;
	}
	
/**
	 * This function generate the html of quantity
	 * @param int $quantity
	 * @param int $cntStock
	 * @return string html
	 */
	public function setQuantity($quantity, $cntStock=0)
	{
		if (!$quantity || !$cntStock)
			return "";
		
		$strHTML = "";
		for($i=1;$i<=$cntStock;$i++){
			$selected = ($i == $quantity) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>\n';
		}
		
		return $strHTML;
	}
	
	private function getColour()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_colour` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['title'] = $objRd->title;
		}
		return $dataArray;
	}
	
	private function setSize($size,$size_ids)
	{
		$sizeList	= $this->getSize();
		$sizes		= explode(",", $size_ids);
		
		$strHTML = "";
		for($i=0;$i<count($sizes);$i++){
			$key  	  = $sizes[$i];
			$selected = ($size == $key) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$key.'" '.$selected.'>'.$sizeList[$key]['size'].'</option>\n';
		}
		
		return $strHTML;
	}
	
	private function getSize()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_size` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['size'] = $objRd->size;
		}
		return $dataArray;
	}
}
?>